
from django.shortcuts import render, HttpResponse, reverse, redirect
from django.db.models import Q

from app01 import models

from app01 import forms

# Create your views here.

def index(request):

    context = {
        "latest_articles": models.Article.objects.order_by("-view_count"),
        "categories": models.Category.objects.all(),
        "latest_comments": models.Comment.objects.order_by("-create_time"),
        "carousels": models.Carousel.objects.order_by("-pk"),
    }

    return render(request, "index.html", context)


def article(request, pk):

    article = models.Article.objects.filter(pk=pk).first()

    if not article:
        return HttpResponse(status=404)

    article.view_count += 1
    article.save()

    context = {
        "article": article
    }
    return render(request, "article.html", context)


def category(request, main_id, sub_id):



    if not main_id:
        return HttpResponse(status=404)


    category = models.Category.objects.filter(pk=main_id).first()

    if not category:
        return HttpResponse(status=404)

    if sub_id:
        articles = models.Article.objects.filter(subcategory_id=sub_id)

    else:
        articles = models.Article.objects.filter(category_id=main_id)

    articles = articles.order_by("-create_time")


    context = {
        "category": category,
        "articles": articles,
    }
    return render(request, "category.html", context)


def login(request):
    error = ""

    if request.session.get("logged_in"):
        return redirect(reverse("index"))

    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")

        user = models.User.objects.filter(
            username=username,
            password=password
        ).first()

        if user:

            request.session["user_id"] = user.pk
            request.session["logged_in"] = True

            url = request.GET.get("url")

            return redirect('index')

        else:
            error = "用户名或密码错误"

    context = {"error": error}
    return render(request, "login.html", context)


def logout(request):
    request.session.delete()
    return redirect(reverse("index"))


def comment(request, article_id):

    content = request.POST.get("content")

    models.Comment.objects.create(
        article_id=article_id,
        content=content,
        author=request.current_user
    )


    return redirect(reverse("article", args=(article_id,)))


def search(request):
    keyword = request.GET.get("query")


    articles = models.Article.objects.filter(
        Q(content__icontains=keyword) | \
        Q(title__icontains=keyword) | \
        Q(author__username__icontains=keyword) | \
        Q(title__icontains=keyword) | \
        Q(category__title__icontains=keyword) | \
        Q(subcategory__title__icontains=keyword) | \
        Q(tags__title__icontains=keyword) \
    ).distinct()



    context = {
        "articles": articles
    }

    return render(request, "search.html", context)




def article_list(request):

    context = {
        "articles": models.Article.objects.filter(author=request.current_user),
    }

    return render(request, "article_list.html", context)


def article_add(request):

    form_obj = forms.ArticleForm()

    if request.method == "POST":
        article = models.Article(author=request.current_user)
        form_obj = forms.ArticleForm(request.POST, request.FILES, instance=article)

        if form_obj.is_valid():
            form_obj.save()
            return redirect(reverse("article_list"))


    context = {"form_obj": form_obj}

    return render(request, "article_add.html", context)


def article_edit(request, pk):

    article = models.Article.objects.filter(pk=pk, author=request.current_user).first()

    form_obj = forms.ArticleForm(instance=article)

    if request.method == "POST":
        form_obj = forms.ArticleForm(request.POST, request.FILES, instance=article)

        if form_obj.is_valid():
            form_obj.save()
            return redirect(reverse("article_list"))


    context = {"form_obj": form_obj}

    return render(request, "article_edit.html", context)



def article_delete(request, pk):

    models.Article.objects.filter(pk=pk, author=request.current_user).delete()

    return redirect(reverse("article_list"))




def category_list(request):

    context = {
        "categories": models.Category.objects.all(),
    }

    return render(request, "category_list.html", context)


def category_add(request):

    context = {}

    if request.method == "POST":
        models.Category.objects.create(title=request.POST.get("category"))
        return redirect(reverse("category_list"))

    return render(request, "category_add.html", context)


def category_edit(request, pk):

    category = models.Category.objects.filter(pk=pk).first()

    context = {"category": category}

    if request.method == "POST":
        category.title=request.POST.get("category")
        category.save()

        return redirect(reverse("category_list"))

    return render(request, "category_edit.html", context)


def category_delete(request, pk):

    models.Category.objects.filter(pk=pk).delete()

    return redirect(reverse("category_list"))





def subcategory_list(request):

    context = {
        "subcategories": models.Subcategory.objects.all(),
    }

    return render(request, "subcategory_list.html", context)


def subcategory_add(request):

    form_obj = forms.SubcategoryForm()

    if request.method == "POST":
        form_obj = forms.SubcategoryForm(request.POST)

        if form_obj.is_valid():
            form_obj.save()
            return redirect(reverse("subcategory_list"))


    context = {"form_obj": form_obj}

    return render(request, "subcategory_add.html", context)


def subcategory_edit(request, pk):
    subcategory = models.Subcategory.objects.get(pk=pk)

    form_obj = forms.SubcategoryForm(instance=subcategory)

    if request.method == "POST":
        form_obj = forms.SubcategoryForm(request.POST, instance=subcategory)

        if form_obj.is_valid():
            form_obj.save()
            return redirect(reverse("subcategory_list"))


    context = {"form_obj": form_obj}

    return render(request, "subcategory_edit.html", context)


def subcategory_delete(request, pk):

    models.Subcategory.objects.filter(pk=pk).delete()

    return redirect(reverse("subcategory_list"))





def tag_list(request):

    context = {
        "tags": models.Tag.objects.all(),
    }

    return render(request, "tag_list.html", context)


def tag_add(request):

    context = {}

    if request.method == "POST":
        models.Tag.objects.create(title=request.POST.get("tag"))
        return redirect(reverse("tag_list"))

    return render(request, "tag_add.html", context)


def tag_edit(request, pk):

    tag = models.Tag.objects.filter(pk=pk).first()

    context = {"tag": tag}

    if request.method == "POST":
        tag.title=request.POST.get("tag")
        tag.save()

        return redirect(reverse("tag_list"))

    return render(request, "tag_edit.html", context)


def tag_delete(request, pk):

    models.Tag.objects.filter(pk=pk).delete()

    return redirect(reverse("tag_list"))





def carousel_list(request):

    context = {
        "carousels": models.Carousel.objects.all(),
    }

    return render(request, "carousel_list.html", context)


def carousel_add(request):

    form_obj = forms.CarouselForm()

    if request.method == "POST":
        form_obj = forms.CarouselForm(request.POST, request.FILES)

        if form_obj.is_valid():
            form_obj.save()
            return redirect(reverse("carousel_list"))


    context = {"form_obj": form_obj}

    return render(request, "carousel_add.html", context)


def carousel_edit(request, pk):
    carousel = models.Carousel.objects.get(pk=pk)

    form_obj = forms.CarouselForm(instance=carousel)

    if request.method == "POST":
        form_obj = forms.CarouselForm(request.POST, request.FILES, instance=carousel)

        if form_obj.is_valid():
            form_obj.save()
            return redirect(reverse("carousel_list"))


    context = {"form_obj": form_obj}

    return render(request, "carousel_edit.html", context)


def carousel_delete(request, pk):

    models.Carousel.objects.filter(pk=pk).delete()

    return redirect(reverse("carousel_list"))


